<template>
  <el-card class="chart-container" shadow="never">
    <chart-filter />

    <el-tabs @tab-click="onSwitchTab">
      <el-tab-pane label="访问量">
        <div class="chart-pic">
          <div class="echart">
            <k-echarts :option="chartOption" />
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="用户增长" name="user">
        <div class="chart-pic">
          <div class="echart">
            <k-echarts :option="chartOption" v-if="activeUser" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script lang="ts">
import { defineComponent, onMounted, onUnmounted, ref } from 'vue'
import ChartFilter from './chart-filter.vue'
import KEcharts from '@/components/echarts/echarts.vue'
import { EChartsOption } from 'echarts/types/dist/echarts'
import { getHomeChartData } from '@/services/home.service'

export default defineComponent({
  name: 'HomeChart',
  components: { KEcharts, ChartFilter },
  setup () {
    const months: string[] = []
    const t = ref<number>(0)
    const activeUser = ref(false)
    for (let i = 1; i <= 12; i++) {
      // series.push(random.int(0, 3000))
      months.push(`${i}月`)
    }
    const chartOption = ref<EChartsOption>({
      color: [
        '#6395F9'
      ],
      tooltip: {
        show: true
      },
      xAxis: {
        type: 'category',
        data: months
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: [],
          type: 'line'
        }
      ]
    })

    const onSwitchTab = (tab: any) => {
      if (tab.index === '1') {
        activeUser.value = true
      }
    }

    const updateChart = async () => {
      const data = await getHomeChartData()
      chartOption.value = {
        ...chartOption.value,
        series: [
          {
            data: data.visits,
            type: 'line'
          }
        ]
      }
    }

    onMounted(async () => {
      await updateChart()
      t.value = setInterval(updateChart, 3000)
    })

    onUnmounted(() => {
      clearInterval(t.value)
    })

    return {
      activeUser,
      chartOption,
      onSwitchTab
    }
  }
})
</script>

<style scoped lang="scss">
.chart {
  &-container {
    margin: 0 24px;
    position: relative;
  }
}
.echart {
  margin: 0 auto;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  ::v-deep(.k-echart) {
    width: 100%;
    height: 100%;
  }
}
.chart-pic {
  position: relative;
  width: 100%;
  height: 400px;
}
</style>
